<!--
 * @Author: yangchao
 * @Date: 2023-05-16 20:00:37
 * @LastEditors: yangchao yangchao@kgcure.com
 * @LastEditTime: 2023-05-29 12:09:13
 * @Description: 这里是描述
-->
<template>
  <div class="app-container page-wiki">
    <div class="left">
      <el-tree
        :data="treeData"
        :props="defaultProps"
        highlight-current
        node-key="id"
        @current-change="onChange"
        :expand-on-click-node="false"
        ref="tree"
      >
        <span class="custom-tree-node" slot-scope="{ node, data }">
          <span>{{ node.label }}</span>
          <span class="btn-group">
            <el-button
              icon="el-icon-plus"
              type="primary"
              circle
              size="mini"
              @click.stop="() => append(data)"
              style="padding: 3px; margin-left: 20px"
            >
            </el-button>
            <el-button
              icon="el-icon-edit"
              type="primary"
              circle
              size="mini"
              @click.stop="() => edit(data)"
              style="padding: 3px; margin-left: 5px"
            >
            </el-button>
          </span> </span
      ></el-tree>
    </div>
    <div class="right" v-if="currentClassify">
      <el-form label-width="80px" inline size="small" @sumbit.native.prevent>
        <el-form-item label="标准问题">
          <el-input v-model="form.key" placeholder="请输入标准问题">
            <el-button
              slot="append"
              icon="el-icon-search"
              @click="onSearch"
            ></el-button>
          </el-input>
        </el-form-item>
        <el-button type="primary" size="small" @click="doAction('add')"
          >新建问题</el-button
        >
      </el-form>
      <el-table :data="tableData" style="width: 100%">
        <el-table-column label="标准问题">
          <template slot-scope="scope">
            <el-link type="primary" @click="doAction('detail', scope.row)">{{
              scope.row.question
            }}</el-link>
          </template>
        </el-table-column>
        <el-table-column label="热度" prop="heat"> </el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-button size="mini" @click="doAction('edit', scope.row)"
              >编辑</el-button
            >
            <el-button
              size="mini"
              type="danger"
              @click="doAction('drop', scope.row)"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <!-- <el-pagination
        style="margin-top: 20px; text-align: right"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page.sync="pager.pageIndex"
        :page-sizes="pager.sizes"
        :page-size.sync="pager.pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="pager.total"
      >
      </el-pagination> -->
    </div>

    <el-dialog
      :title="leftForm.classifyId ? '编辑分类' : '添加分类'"
      :visible.sync="leftVisible"
      width="30%"
    >
      <el-form
        label-width="80px"
        size="small"
        :model="leftForm"
        :rules="leftRules"
        ref="leftForm"
      >
        <el-form-item label="分类名称" prop="name">
          <el-input v-model="leftForm.name" placeholder="请输入"></el-input>
        </el-form-item>
        <el-form-item label="排序" prop="sortId">
          <el-input-number
            :min="1"
            v-model="leftForm.sortId"
            placeholder="请输入"
            style="width: 100%"
          ></el-input-number>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="leftVisible = false">取 消</el-button>
        <el-button type="primary" @click="addClassfy">确 定</el-button>
      </span>
    </el-dialog>
    <el-dialog :title="title" :visible.sync="rightVisible" width="30%">
      <el-form
        label-width="80px"
        size="small"
        :model="rightForm"
        :rules="rightRules"
        :disabled="title == '查看详情'"
        ref="rightForm"
        v-if="currentClassify"
      >
        <el-form-item label="标准问题" prop="question">
          <el-input
            v-model="rightForm.question"
            placeholder="请输入"
          ></el-input>
        </el-form-item>
        <el-form-item label="答案" prop="content">
          <el-input
            v-model="rightForm.content"
            placeholder="请输入"
            type="textarea"
          ></el-input>
        </el-form-item>
        <el-form-item label="分类" prop="classifyId">
          <el-input
            :value="getClassifyName(rightForm.classifyId)"
            placeholder="请输入"
            disabled
          ></el-input>
          <el-input
            v-model="rightForm.classifyId"
            placeholder="请输入"
            disabled
            v-show="false"
          ></el-input>
        </el-form-item>
        <el-form-item label="关键词" prop="labels">
          <el-input
            v-model="rightForm.labels"
            placeholder="请输入关键字，以英文逗号分隔"
          ></el-input>
        </el-form-item>
        <el-form-item label="热度" prop="heat">
          <el-input v-model="rightForm.heat" placeholder="请输入"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="rightVisible = false">取 消</el-button>
        <el-button type="primary" @click="addDocs">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import {
  getClassify,
  getClassifyDocs,
  createClassfy,
  updateClassfy,
  searchDocs,
  addDoc,
  updateDoc,
  delDoc,
} from "@/api/wiki/index";
export default {
  name: "WiKi",
  components: {},
  data() {
    return {
      treeData: [],
      defaultProps: {
        children: "children",
        label: "name",
      },
      form: {
        key: "",
      },
      tableData: [],
      pager: {
        pageIndex: 1,
        pageSize: 10,
        sizes: [10, 20, 50, 100],
        total: 96,
      },
      leftVisible: false,
      rightVisible: false,
      leftForm: {
        name: "",
        sortId: null,
        classifyId: "",
      },
      leftRules: {
        name: [
          {
            required: true,
            message: "不能为空",
            trigger: "blur",
          },
        ],
      },
      rightForm: {
        question: "",
        content: "",
        classifyId: "",
        labels: "",
        heat: "",
      },
      rightRules: {
        question: [
          {
            required: true,
            message: "不能为空",
            trigger: "blur",
          },
        ],
        content: [
          {
            required: true,
            message: "不能为空",
            trigger: "blur",
          },
        ],
        classifyId: [
          {
            required: true,
            message: "不能为空",
            trigger: "blur",
          },
        ],
        // labels: [
        //   {
        //     required: true,
        //     message: "不能为空",
        //     trigger: "blur",
        //   },
        // ],
      },
      title: "",
      currentClassify: null,
    };
  },
  created() {
    this.init();
  },
  methods: {
    init() {
      // 初始化
      getClassify(0).then((res) => {
        this.treeData = res.data || [];
        if (this.treeData.length) {
          this.$nextTick(function () {
            this.currentClassify = this.treeData[0];
            const currentKey = this.currentClassify.id;
            this.$refs.tree.setCurrentKey(currentKey);
            this.getClassifyDocs(currentKey);
          });
        }
      });
    },
    getClassifyName(id) {
      const tree = this.handleTreeData(this.treeData);
      return (tree[id] || {}).name;
    },
    handleTreeData(arr = [], obj = {}) {
      if (arr && arr.length) {
        arr.forEach((ele) => {
          const { id, children } = ele;
          obj[id] = ele;
          this.handleTreeData(children, obj);
        });
      }
      return obj;
    },
    // 左侧节点变化
    onChange(data, node) {
      console.log(11111111, data);
      const { id } = data;
      this.currentClassify = data;
      this.getClassifyDocs(id);
    },
    getClassifyDocs(classifyId) {
      const params = {
        classifyId,
        getChildren: 0,
      };
      getClassifyDocs(params).then((res) => {
        const [node] = res.data || [];
        this.tableData = node.docs;
        this.form.key = "";
      });
    },
    append(data) {
      this.leftVisible = true;
      this.leftForm = {
        name: "",
        sortId: null,
        parentId: data.id,
        type: data.type,
      };
    },
    edit(data) {
      this.leftVisible = true;
      this.leftForm = {
        name: data.name,
        sortId: data.sortId,
        classifyId: data.id,
        type: data.type,
      };
    },
    // 添加分类
    addClassfy() {
      this.$refs.leftForm.validate().then(() => {
        if (this.leftForm.classifyId) {
          const data = {
            ...this.leftForm,
            sort: this.leftForm.sortId,
          };
          updateClassfy(data).then((res) => {
            this.$message.success("编辑成功");
            this.leftVisible = false;
            this.init();
          });
        } else {
          const data = {
            ...this.leftForm,
          };
          createClassfy(data).then((res) => {
            this.$message.success("添加成功");
            this.leftVisible = false;
            this.init();
          });
        }
      });
    },
    onSearch() {
      if (this.form.key === "") return this.$message.error("请输入");
      searchDocs(this.form).then((res) => {
        this.tableData = res.data || [];
      });
    },
    handleSizeChange(val) {
      console.log(`每页 ${val} 条`);
    },
    handleCurrentChange(val) {
      console.log(`当前页: ${val}`);
    },
    doAction(type, row) {
      switch (type) {
        case "add":
          this.rightVisible = true;
          this.title = "添加问题";
          this.rightForm = {
            question: "",
            content: "",
            classifyId: this.currentClassify.id,
            labels: "",
            heat: "",
          };
          break;
        case "edit":
          this.rightVisible = true;
          this.title = "编辑问题";
          this.rowId = row.id;
          this.rightForm = {
            ...row,
            classifyId: row.classId,
          };
          break;
        case "detail":
          this.rightVisible = true;
          this.title = "查看详情";
          this.rightForm = {
            ...row,
            classifyId: row.classId,
          };
          break;
        case "drop":
          const data = {
            docId: row.id,
          };
          this.$confirm("确认删除？", "系统提示").then(() => {
            delDoc(data).then(() => {
              this.$message.success("删除成功");
              this.getClassifyDocs(this.currentClassify.id);
            });
          });
          break;

        default:
          break;
      }
    },
    addDocs() {
      this.$refs.rightForm.validate().then(() => {
        if (this.title == "添加问题") {
          const data = {
            ...this.rightForm,
            labels:
              this.rightForm.labels == ""
                ? []
                : this.rightForm.labels.split(","),
          };
          addDoc(data).then((res) => {
            this.$message.success("添加成功");
            this.rightVisible = false;
            this.getClassifyDocs(this.rightForm.classifyId);
          });
        } else if (this.title == "编辑问题") {
          const data = {
            ...this.rightForm,
            docId: this.rowId,
            labels:
              this.rightForm.labels == ""
                ? []
                : this.rightForm.labels.split(","),
          };
          updateDoc(data).then((res) => {
            this.$message.success("编辑成功");
            this.rightVisible = false;
            this.getClassifyDocs(this.rightForm.classifyId);
          });
        }
      });
    },
  },
};
</script>

<style lang="scss">
.page-wiki {
  height: calc(100vh - 50px);
  display: flex;
  .left {
    width: 300px;
    border-right: 1px solid #e6e6e6;
  }
  .right {
    flex: 1;
    padding: 0 10px;
  }
  .custom-tree-node {
    &:hover {
      .btn-group {
        visibility: visible;
      }
    }
    .btn-group {
      visibility: hidden;
    }
  }
}
</style>
